package com.laot.search.utils;

import cn.hutool.core.util.RandomUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem;
import org.laot.seacher_master.model.common.ErrorCode;
import org.laot.seacher_master.model.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;

@Slf4j
@Component
@ConfigurationProperties(prefix = "oss")
public class OssUtils {
    private String accessKey;
    private String secretKey;
    private String bucket;

    @Value("${oss.url}")
    private String url;
    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }
    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }
    public void setBucket(String bucket) {
        this.bucket = bucket;
    }


    public String uploadUtil(MultipartFile file){
        //构造一个带指定 Region 对象的配置类
        //修改1.Region指定数据存储区域，autoRegion()自动根据七牛云账号找到选的区域（我选的是 华北）
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //指定上传到oss时文件名称
        String key = null;
        try {
            //修改5 注释掉，默认上传 字符串，写我们自己的上传格式（上传图片）
            //            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            //            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            //上传文件——图片格式（本机绝对路径）
            InputStream inputStream = file.getInputStream();

            //拿到文件类型
            key = file.getOriginalFilename();
            String pre = System.currentTimeMillis()+RandomUtil.randomNumbers(5);
            key = pre+"/"+key;
            Auth auth = Auth.create(accessKey, secretKey);//创建凭证
            String upToken = auth.uploadToken(bucket); //上传凭证

            try {
                //修改6 put方法 第一个参数 要放上面 自己定义的 inputStream对象
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                log.info("存储的链接是"+url+putRet.key); //Fo2AVLRHugoNbek6XZ8Uy-DCnuSL hash值就是上传后的图片名字
                return url+putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传文件时失败，失败原因是："+r.bodyString());
            }
        } catch (Exception ex) {
            //ignore  异常类型 改大一点
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传文件时失败，失败原因是："+ex);
        }

    }



}
